<template>
  <div class="callback">
    登陆成功，此窗口即将关闭。。。
  </div>
</template>

<script setup name="Callback">
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { getToken as getCodeToken, getInfo, logOut } from "@/api/token";
const router = useRouter();
// 定义响应式变量来存储查询参数
const code = ref(null);
const state = ref(null);
const issuer = ref(null);
onMounted(async () => {
    // 获取当前 URL
      const urlParams = new URLSearchParams(window.location.search)
    // 提取查询参数
    code.value = urlParams.get("code");
    state.value = urlParams.get("state");
    issuer.value = urlParams.get("iss");
    await getToken(urlParams);
    const userInfo = await getInfo();
    // 发送用户信息和权限到主窗口
    window.opener && window.opener.postMessage(
        {
            type: 'auth-success',
            userInfo,
        },
        '*'
    );
    window.close();
});

const getToken = async (urlParams) => {
    if (!code.value) {
        alert({
            type: "danger",
            message: "授权码未找到",
        });
        return;
    }
    const codeVerifier = localStorage.getItem("code_verifier");
    if (!codeVerifier) {
       alert({
            type: "danger",
            message: "code_verifier未找到",
        });
        return;
    }
    const callbackPath = router.resolve({ path: "/callback" }).href;
    const absoluteCallbackUrl = window.location.origin + callbackPath;

    try {
        const params = new URLSearchParams({
            grant_type: "authorization_code",
            code: code.value,
            redirect_uri: absoluteCallbackUrl,
            client_id: import.meta.env.VITE_OPENIDDICT_CLIENT_ID,
            client_secret: import.meta.env.VITE_OPENIDDICT_CLIENT_SECRET,
            code_verifier: codeVerifier, // 必须提供！
        });
        const tokenResponse = await getCodeToken(params);
        localStorage.setItem("tokenResponse", JSON.stringify(tokenResponse));
        localStorage.setItem("token", tokenResponse.access_token);
        localStorage.setItem("refresh_token", tokenResponse.refresh_token);
        return tokenResponse.access_token;
    } catch (error) {
        console.error("Error exchanging authorization code for tokens:", error);
    }
};


</script>

<style scoped>
.callback {
  text-align: center;
  padding: 2rem;
}

.callback-info {
  margin: 2rem 0;
  padding: 1rem;
  background-color: #f5f5f5;
  border-radius: 8px;
  display: inline-block;
  text-align: left;
}

.callback-info ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.callback-info li {
  padding: 0.25rem 0;
  word-break: break-all;
}

.nav-link {
  display: inline-block;
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  color: #42b883;
  text-decoration: none;
  border: 1px solid #42b883;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #42b883;
  color: white;
}
</style>